﻿
namespace AspNetCoreWebMiddleware.Middleware
{
    public class JsMiddlewares 
    {
        private RequestDelegate next;

        public JsMiddlewares(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var path = context.Request.Path.Value;
            if (path.Equals("/js"))
            {
                //await ResposeJs(context);
                throw new Exception("执行异常");
                await ResposeJs(context);
            }
            else
            {
                // 2、给下一个中间件
                await next(context);
            }
        }

        public static async Task ResposeJs(HttpContext httpContext)
        {
            // 设置响应内容类型为
            httpContext.Response.ContentType = "application/javascript";

            // 获取 JavaScript 文件的路径
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "index.js");

            // 读取 JavaScript 文件内容
            var jsContent = await File.ReadAllTextAsync(filePath);

            // 响应 JavaScript 文件内容
            await httpContext.Response.WriteAsync(jsContent);
        }
    }
}
